package org.example.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 用于sharding分表的类 by id取模
 *
 */
@Component
public class CustomShardingTableAlgorithm implements PreciseShardingAlgorithm<Long>, RangeShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        Long index = preciseShardingValue.getValue() % collection.size() + 1;
        for(String database : collection) {
            if(database.endsWith(index + "")) {
                return database;
            }
        }
        return null;
    }

    /**
     * 用于范围查询
     * @param collection 数据库集合
     * @param rangeShardingValue 指定范围 for example select * from between ? and ?
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {

        Long lowerId = rangeShardingValue.getValueRange().lowerEndpoint();
        Long upperId = rangeShardingValue.getValueRange().upperEndpoint();

        Collection<String> result = new ArrayList<>();
        for(Long i = lowerId; i <= upperId; i++) {
            long index = i % collection.size();
            for(String database : collection) {
                database.endsWith(index + "");
                result.add(database);
            }
        }

        return result;
    }
}